﻿using Spire.Pdf;
using System;
using System.Windows.Forms;

namespace PdfOperator
{
    public partial class FrmPdfToImg : Form
    {
        public FrmPdfToImg()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 打开PDF
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnOpenfile_Click(object sender, EventArgs e)
        {
            OpenFileDialog fileDialog = new OpenFileDialog();
            fileDialog.Title = "打开PDF";
            fileDialog.Filter = "pdf文件|*.pdf";
            if (fileDialog.ShowDialog() == DialogResult.OK)
            {
                string name = fileDialog.FileName;
                txtFilePath.Text = name;
            }
        }

        /// <summary>
        /// 选择保存路径
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSavePath_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog folderBrowser = new FolderBrowserDialog();
            folderBrowser.Description = "选择图片保存路径";
            if (folderBrowser.ShowDialog() == DialogResult.OK)
            {
                txtSavePath.Text = folderBrowser.SelectedPath;
            }
        }

        /// <summary>
        /// pdf转图片
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnStart_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtFilePath.Text))
            {
                MessageBox.Show("请选择要操作的PDF文件！");
                return;
            }

            //初始化PdfDocument实例
            PdfDocument doc = new PdfDocument();
            //加载PDF文档
            doc.LoadFromFile(txtFilePath.Text);
            //遍历PDF每一页
            for (int i = 0; i < doc.Pages.Count; i++)
            {
                //将PDF页转换成bitmap图形
                System.Drawing.Image bmp = doc.SaveAsImage(i);

                //将bitmap图形保存为png图片
                string fileName = string.Format(txtSavePath.Text + "\\PDF转图片Page{0}.png", i + 1);
                bmp.Save(fileName, System.Drawing.Imaging.ImageFormat.Png);
            }
            MessageBox.Show("完成");
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        /// <summary>
        /// 打开文件夹
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnOpenFolder_Click(object sender, EventArgs e)
        {
            //判断文件是否存在
            if (!System.IO.Directory.Exists(txtSavePath.Text))
            {
                return;
            }
            else
            {
                //存在文件夹
                System.Diagnostics.Process.Start("explorer.exe", txtSavePath.Text);
            }
            
        }
    }
}
